package com.gitee.wsl.android.ui.ext

import android.graphics.RectF
import android.widget.ImageView
import java.lang.Math.min

/**
 * fit image into a [rect]
 * @param rect a position relative to [ImageView] in percentage
 */
fun ImageView.fitIntoRect(rect: RectF? = null) {
    post {
        val r = rect ?: RectF(0f, 0f, 1f, 1f)
        scaleType = ImageView.ScaleType.MATRIX
        imageMatrix = imageMatrix.apply {
            val (imgWidth, imgHeight) = drawable?.let { it.minimumWidth to it.intrinsicHeight } ?: return@post
            val scaleX = r.width() * measuredWidth / imgWidth.toFloat()
            val scaleY = r.height() * measuredHeight / imgHeight.toFloat()
            val scale = min(scaleX, scaleY)
            postScale(scale, scale)
            val dx = r.centerX() * measuredWidth - scale * imgWidth / 2
            val dy = r.centerY() * measuredHeight - scale * imgHeight / 2
            postTranslate(dx, dy)
        }
    }
}